package com.cyzy.filters;


import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final String[] WHITE_LIST = {
            "/user/login",
            "/user/register",
            "/user/phoneLogin",
            "/user/getPhoneCode",
            "/user/getCode",
            "/driver/login",
            "/driver/register",
            "/driver/getPhoneCode",
            "/driver/phoneLogin",
            "/driver/getCode",
            "/recognition/uploadDrivingLicenseImg",
            "/recognition/uploadIdNum",
            "/recognition/uploadPermitImg"
    };
    private AntPathMatcher matcher = new AntPathMatcher();

    private boolean isWhiteListed(String path) {
        for (String pattern : WHITE_LIST) {
            if (matcher.match(pattern, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();
        System.out.println("请求路径：" + url);

        // 1. 白名单放行
        if (isWhiteListed(url)) {
            return chain.filter(exchange);
        }

        // 2. 获取 token
        List<String> list = request.getHeaders().get("Authorization");
        System.out.println(list+"----------------------");
        if (list == null || list.isEmpty()) {
            return unauthorizedResponse(exchange, "token不能为空");
        }

        String token = list.get(0);
        System.out.println(token);
        Boolean exists = redisTemplate.hasKey(token);
        if (Boolean.FALSE.equals(exists)) {
            return unauthorizedResponse(exchange, "token无效或已过期");
        }
        System.out.println("放行");
        // 3. 放行
        return chain.filter(exchange);
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 401);
        map.put("message", message);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONString(map).getBytes());
        return response.writeWith(Mono.just(buffer));
    }
}
